<template>
  <div id="mqttws">
    <div id="onlineIcon" :class="{online:online}"></div>
    <!-- <div id="networks" ref="networks" @click="openClose">
      <dl v-for="item in messageListPlay">
        收到消息：{{item}}
      </dl>
    </div> -->
  </div>
</template>
<script>
  import api from "@/common/api"
  import filter from "@/assets/location-filter"
  export default {
    name: 'mqttws',
    inject: ["reload"],
    data() {
      return {
        messageListPlay: ["当前无消息"],
        openNetworks: true,
        online: false,
        // client : new Paho.MQTT.Client("192.168.0.240", 8083, "admin"),//第三个参数是clientID可以为空
        client : {},//第三个参数是clientID可以为空
        topic: "limitInfo/admin", // 订阅的主题
        sendTopic: "geolocation/admin",
        messageTopic: "message/admin",
        taskTopic: "task/admin",
        appExit: "appExit/admin",
        xSpeed: 9999,
        sendInterval: null,
        mineSpeedInterval: null,
        mineSpeed: -1,
        mFilter: null,
        taskId: null,
        requestOnce: true,
        preSpeed: null, // 上一次的速度
        flagID: null, // 防止重复播报FLAG
        networksList: [], // 网络日志
        pUser: null// 用户位置对象存储
      }
    },
    mounted () {
      // 消息push推送事件监听
      let _this = this;
      _this.mFilter = new filter.GpsSimpleFilter; // 定位过滤器
      document.addEventListener("plusready",function(){
        _this.plusReady();
        _this.watchGeolocation();
      },false);
    },
    methods: {
      openClose () {
        this.openNetworks = !this.openNetworks;
        this.openNetworks ? this.$refs.networks.style.top = "0px" : this.$refs.networks.style.top = "-35%";
      },
      autoOnline () {
        //连接服务器并注册连接成功处理事件
        this.client.connect({onSuccess:this.onConnect, onFailure:this.onOnlineFailure});
        //注册连接断开处理事件
        this.client.onConnectionLost = this.onConnectionLost;
        //注册消息接收处理事件
        this.client.onMessageArrived = this.onMessageArrived;
        this.client.onMessageDelivered = this.onMessageDelivered;
        this.mySetInterval(this.$store.state.interval);
        this.speedMsg();
      },
      speedMsg () {
        // 超速提醒
        clearInterval(this.mineSpeedInterval);
        this.mineSpeedInterval = setInterval(() => {
          if(this.mineSpeed > this.xSpeed && this.preSpeed !== this.mineSpeed){
            this.preSpeed = this.mineSpeed;
            this.common.tts('您已超速，当前速度：'+ this.mineSpeed + "。当前限速："+ this.xSpeed);
            // 数据返回
            if(this.requestOnce){
              this.requestOnce = false;
              this.common.reqData(api.app('taskUpdate'), Object.assign({},this.$store.state.user,{
                content:{
                  taskID: this.taskId,
                  mineSpeed: this.mineSpeed,
                  xSpeed: this.xSpeed
                }
              }), res=>{
                console.log(res);
                this.requestOnce = true;
              },err =>{
                  this.requestOnce = true;
                  console.log(err)
                  this.Toast.clear();
              });
            }
          }
        }, 5000);
      },
      onConnectionLost:function (responseObject) {
        if (responseObject.errorCode !== 0) {
          console.log("<MQTT连接已断开>:" + responseObject.errorMessage);
          this.online = false;
          clearInterval(this.sendInterval);
          clearInterval(this.mineSpeedInterval);
          this.autoOnline();
        }
      },
      onMessageArrived: function(message) {
        console.log("<收到消息>:", message.payloadString);
        // this.messageListPlay.push(message.payloadString + ' ' + (new Date()).toLocaleString());
        let type = message.destinationName;
        console.log("type", type);
        if(type.indexOf('limit') >= 0){
          // 限速
          this.xSpeed = parseFloat(message.payloadString.split(",")[0]);
          this.taskId = message.payloadString.split(",")[1];
          return;
        }else if(type.indexOf('message') >= 0){
          // 碰撞
          let numberId = parseFloat(message.payloadString.split(",")[0]);
          let payloadString = message.payloadString.substring(message.payloadString.indexOf(",")+1,message.payloadString.length);
          if(numberId == this.flagID){
            return false;
          }else{
            this.flagID = numberId;
            // 任务
            this.common.tts(payloadString);
          } //相等就返回
          return;
        }else if(type.indexOf('task') >= 0){
          let numberId = parseFloat(message.payloadString.split(",")[0]);
          let payloadString = message.payloadString.substring(message.payloadString.indexOf(",")+1,message.payloadString.length);
          if(numberId == this.flagID){
            return false;
          }else{
            this.flagID = numberId;
            // 任务
            this.common.tts(payloadString);
            if(window.plus) {this.createLocalPushMsg(payloadString)};
            if(payloadString.indexOf("移位") >= 0){
              if(this.$route.path == "/transposing"){
                this.reload();
              }else{
                this.$router.push({name:'transposing'});
              }
            }
            if(payloadString.indexOf("挑車出库") >= 0){
              if(this.$route.path == "/outlibrary"){
                this.reload();
              }else{
                this.$router.push({name:'outlibrary'});
              }
            }
            if(payloadString.indexOf("借車出库") >= 0){
              if(this.$route.path == "/outlibrary"){
                this.reload();
              }else{
                this.$router.push({name:'outlibrary'});
              }
            }
            if(payloadString.indexOf("移库出库") >= 0){
              if(this.$route.path == "/outlibrary"){
                this.reload();
              }else{
                this.$router.push({name:'outlibrary'});
              }
            }
            if(payloadString.indexOf("收车") >= 0){
              if(this.$route.path == "/pickcar"){
                this.reload();
              }else{
                this.$router.push({name:'pickcar'});
              }
            }
          } //相等就返回
        }else if(type.indexOf('appExit') >= 0){
          this.common.tts(message.payloadString.split(',')[1]);
          this.$router.push({name:'login'});
        }
      },
      onMessageDelivered: function(message) {
        // console.log("已发送消息:" + message.payloadString);
      },
      onOnlineFailure (error) {
        this.online = false;
        console.log("<MQTT连接失败>" + JSON.stringify(error));
        // 网络测试
        var nt = plus ? plus.networkinfo.getCurrentType() : null;
        if(!plus){return;}
        var networksLog = -1;
        switch (nt){
          case plus.networkinfo.CONNECTION_ETHERNET:
          case plus.networkinfo.CONNECTION_WIFI:
            networksLog = 0;
            console.log("Switch to Wifi networks!");
          break;
          case plus.networkinfo.CONNECTION_CELL2G:
          case plus.networkinfo.CONNECTION_CELL3G:
          case plus.networkinfo.CONNECTION_CELL4G:
            networksLog = 1;
            console.log("Switch to Cellular networks!");
          break;
          default:
            networksLog = 2;
            console.log("Not networks!");
          break;
        }
        if(networksLog === 0){
          this.networksList.push({
            info: "WIFI",
            time: (new Date()).toLocaleString(),
            errorCode: error.errorCode,
            errorMessage: error.errorMessage
          });
        }else if(networksLog === 1){
          this.networksList.push({
            info: "移动网络",
            time: (new Date()).toLocaleString(),
            errorCode: error.errorCode,
            errorMessage: error.errorMessage
          });
        }else if(networksLog === 2){
          this.networksList.push({
            info: "无网络",
            time: (new Date()).toLocaleString(),
            errorCode: error.errorCode,
            errorMessage: error.errorMessage
          });
        }
        clearInterval(this.sendInterval);
        clearInterval(this.mineSpeedInterval);
        // 重新连接
        setTimeout(() => {
          this.autoOnline();
        }, 5000);
      },
      onConnect : function() {
        console.log("<已连接MQTT>");
        //this.client.disconnect(); // 断开连接
        this.online = true;
        this.client.subscribe(this.topic, {qos:2});//订阅主题
        this.client.subscribe(this.messageTopic, {qos:2});//订阅主题
        this.client.subscribe(this.taskTopic, {qos:2});//订阅主题
        this.client.subscribe(this.appExit, {qos:2});//订阅主题
      },
      sendMsg (options) {
        // 发消息
        let message = new Paho.MQTT.Message(JSON.stringify(options));
        message.destinationName = this.sendTopic;
        this.client.send(message);
      },
      plusReady () {
        var info = plus.push.getClientInfo();
        console.log( "手机用户信息: " + JSON.stringify( info ) );
        let _this = this;
        _this.mFilter.reset(); // 重置过滤器
        // 添加监听从系统消息中心点击消息启动事件
        plus.push.addEventListener( "click", function ( msg ) {
          console.log(msg);
          let type = msg.content.split('[')[1].split("]")[0];
          switch (type) {
            case "收车":
              _this.$router.push({name:'pickcar'});
              break;
            case "乘车":
              _this.$router.push({name:'callcar'});
              break;
            case "交通车":
              _this.$router.push({name:'trafficcar'});
              break;
            case "出库":
              _this.$router.push({name:'outlibrary'});
              break;
            case "挑車出库":
              _this.$router.push({name:'outlibrary'});
              break;
            case "借車出库":
              _this.$router.push({name:'outlibrary'});
              break;
            case "移库出库":
              _this.$router.push({name:'outlibrary'});
              break;
            case "入库":
              _this.$router.push({name:'inlibrary'});
              break;
            case "移位":
              if(_this.$route.path == "/transposing"){
                _this.reload();
              }else{
                _this.$router.push({name:'transposing'});
              }
              break;
            default:
              return false;
              break;
          }
          plus.push.remove(msg);
          plus.push.clear();
        }, false );
      },
      createLocalPushMsg (message) {
        var options = {cover:false};
        plus.push.createMessage( message, "LocalMSG", options );
        if(plus.os.name == "iOS"){
          console.log('*如果无法创建消息，请到"设置"->"通知"中配置应用在通知中心显示!');
        }
      },
      mySetInterval (time) {
        this.sendInterval = setInterval(() => {
          if(this.online){
            this.pUser ? this.sendMsg({
              "time": this.pUser.time, // 定位时间(时间戳)
              "latitude": this.pUser.latitude, // 经度
              "longitude": this.pUser.longitude, // 纬度
              "speed": this.pUser.speed, // 速度
              "accuracy": this.pUser.accuracy,
              "altitudeAccuracy": this.pUser.altitudeAccuracy,
            }) : console.log('暂未获取到经纬度，无法上传定位信息。');
          }
        }, (time ? time : 5) * 1000);
      },
      watchGeolocation () {
        // 监听实时定位
        let _this = this;
        plus.geolocation.watchPosition(function(p){
          // 当前速度存储
          _this.mineSpeed = parseFloat(p.coords.speed).toFixed(2);
          var mPoint = new filter.Position(new Date(), p.coords.longitude, p.coords.latitude, _this.mineSpeed);
          if(_this.mFilter.nextPosition(mPoint)){
            _this.pUser = {
              latitude: p.coords.latitude,
              longitude: p.coords.longitude,
              accuracy: p.coords.accuracy,
              altitudeAccuracy: p.coords.altitudeAccuracy,
              speed: p.coords.speed,
              time: new Date().getTime()
            };
            // 坐标转换
            // plus.maps.Map.convertCoordinates(new plus.maps.Point(p.coords.longitude, p.coords.latitude), {}, function(event){
            //   var point = event.coord;  // 转换后的坐标值
            // },function(e){
            //   alert("Failed:"+JSON.stringify(e));
            // });
          }
        }, function(e){
          console.log('定位错误: ' + e.message);
        }, {
          coordsType: "bd09ll",
          enableHighAccuracy: true,
          geocode: false,
          provider:'baidu'
        });
      }
    },
    computed: {
      clientId () {
        return this.$store.state.user.clientId;
      }
    },
    watch:{
      clientId: function(data) {
        this.client = new Paho.MQTT.Client(this.$store.state.mqtt, parseInt(this.$store.state.post), this.clientId);
        this.topic = "limitInfo/"+this.clientId;
        this.sendTopic = "geolocation/"+this.clientId;
        this.messageTopic = "message/"+this.clientId;
        this.taskTopic = "task/"+this.clientId;
        this.appExit = "appExit/"+this.clientId;
        this.autoOnline();
      }
    }
  }
</script>
<style>
#mqttws{
  position: absolute;
}
#onlineIcon{
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
  height: 2px;
  background: rgba(247, 4, 37, 0.76);
  z-index: 999;
}
#onlineIcon.online{
  background: rgba(44, 230, 7, 0.726);
}
#networks{
  position: fixed;
  top: 0;
  right: 0;
  background: rgba(0,0,0,0.5);
  width: 100%;
  height: 40%;
  z-index: 99999;
  overflow: auto;
  color: #fff;
  left: 50%;
}
#networks dl{
  border-bottom: 1px solid #fff;
  padding: 10px 0;
}
#mqttws h1{
  padding: 15px 0;
  margin: 0;
  font-size: 1em;
}
</style>
